#include "toysort.h"
#include <Python.h>

void toysort_init(void)
{

	Py_Initialize();
	PyObject *sys = PyImport_ImportModule("sys");
	PyObject *path = PyObject_GetAttrString(sys,"path");
	PyList_Append(path,PyUnicode_FromString(".")); 

}	

void toysort_fin(void)
{
	Py_Finalize();
}

char *toysort_category(char *ty)
{


	PyObject *file = PyImport_ImportModule("toysort");
	if(file == NULL)
	{ 
		PyErr_Print();
		printf("load toysort failed\n");
		goto FAILED_MODULE;
	}
	PyObject *fc = PyObject_GetAttrString(file,"aliyun_type");
	if(fc == NULL)
	{
		PyErr_Print();
		printf("load aliyun_type failed!\n");
		goto FAILED_FUNC;
	}
	PyObject *res = PyObject_CallObject(fc,NULL);
	if(res == NULL)
	{
		PyErr_Print();
		printf("call fc failed!\n");
		goto FAILED_CALL;
	}
    char *rvalue = NULL;
	PyArg_Parse(res,"s",&rvalue);
	ty = (char*)malloc(sizeof(char)*(strlen(rvalue)+1));
	memset(ty,'\0',strlen(rvalue)+1);
	strncpy(ty,rvalue,strlen(rvalue)+1);

   FAILED_CALL:
	Py_DECREF(res);
   FAILED_FUNC:
	Py_DECREF(fc);
   FAILED_MODULE:
	Py_DECREF(file);

   return ty;
}

